package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.common.util.JsonResult;
import cn.wolfcode.luowowo.common.util.KeysUtil;
import cn.wolfcode.luowowo.service.IStrateryStatisRedisService;
import cn.wolfcode.luowowo.service.util.StatisUtil;
import cn.wolfcode.luowowo.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Service
public class StrategyStatisRedisServiceImpl implements IStrateryStatisRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Autowired
    private StatisUtil util;

    @Override
    public void statisAndUpdateViewnum(Long id, int i, int type) {
         util.statisAndUpdateViewnum(id, i, type);
    }

    @Override
    public StatisVO getStatisRedis(String key) {
        return util.getStatisRedis(key);
    }

    @Override
    public JsonResult favor(Long sId, Long uId, int userFavorType) {
        return util.favor(sId, uId, userFavorType);
    }

    @Override
    public JsonResult strategyThumbup(Long sid, Long userInfoId, int userFavorType ) {
        return util.strategyThumbup(sid, userInfoId, userFavorType);
    }

    @Override
    public void setReplynumStatisRedis(Long detailId, int i, String sKey) {
        util.setReplynumStatisRedis(detailId, i, sKey);
    }

    @Override
    public boolean checkFavor(Long id, String ukey) {
        return util.checkFavor(id,ukey);
    }

    @Override
    public List<StatisVO> getCommendVO(String key) {
        Set<String> range = redisTemplate.opsForZSet().reverseRange(key, 0, 9);
        List<StatisVO> list = new ArrayList<>();
        for (String s : range) {
            String s1 = redisTemplate.opsForValue().get(s);
            StatisVO vo = JSON.parseObject(s1, StatisVO.class);
            list.add(vo);
        }
        return list;
    }



    @Override
    public void initRedisStatis() {
        List<StrategyDetail> strategyDetails = strategyDetailService.list();
        for (StrategyDetail detail : strategyDetails) {
            String key = KeysUtil.STRATEGY_STATIS_VO.join(detail.getId().toString());
            if (redisTemplate.hasKey(key)) {
                continue;
            }
            StatisVO vo = new StatisVO();
            util.copyStrategyProperties(detail, vo);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        }
    }

    @Override
    public void redisPersistent() {
        Set<String> strateryKeys = redisTemplate.keys(KeysUtil.STRATEGY_STATIS_VO.getName() + "*");
        for (String key : strateryKeys) {
            String s = redisTemplate.opsForValue().get(key);
            StatisVO vo = JSON.parseObject(s, StatisVO.class);
            StrategyDetail detail = new StrategyDetail();
            try {
                BeanUtils.copyProperties(detail, vo);
                detail.setId(vo.getStrategyId());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            strategyDetailService.updateReidsStatis(detail);
        }

    }

    @Override
    public void initRedisCommend() {
        //从redis中拿的数据才是最真实的
        Set<String> keys = redisTemplate.keys(KeysUtil.STRATEGY_STATIS_VO.getName() + "*");
        String iKey = KeysUtil.INLAND_STRATERY_STATIS_COMMEND_SORT.getName();//国内推荐key
        String fKey = KeysUtil.FOREIGN_STRATERY_STATIS_COMMEND_SORT.getName();//国外推荐key
        String sKey = KeysUtil.STRATERY_STATIS_HOT_COMMEND_SORT.getName();//热门推荐key
        //初始化海内海外推荐
        for (String key : keys) {
            StatisVO vo = getStatisRedis(key);
            //redis有数据直接跳过
            if (redisTemplate.opsForZSet().rank(iKey,
                    key) != null || redisTemplate.opsForZSet().rank(fKey,key) != null) {
                continue;
            }

            double score = vo.getFavornum() + vo.getThumbsupnum();

            //false 为国内
            if (vo.isIsabroad()) {
                redisTemplate.opsForZSet().add(fKey, key, score);
            } else {
                redisTemplate.opsForZSet().add(iKey, key, score);
            }
        }

        //初始化热门推荐
        for (String key : keys) {
            StatisVO vo = getStatisRedis(key);
            if (redisTemplate.opsForZSet().rank(sKey, key) != null) {
                continue;
            }
            double score = vo.getReplynum() + vo.getViewnum();
            redisTemplate.opsForZSet().add(sKey, key, score);
        }
    }






































   /* private final static int VIEWNUM = 1;
    private final static int REPLYNUM = 2;
    private final static int FAVORNUM = 3;
    private final static int SHARENUM = 4;
    private final static int THUMBSUPNUM = 5;*/


    

   /* public StatisVO getStatisRedis(String key) {
        return JSON.parseObject(redisTemplate.opsForValue().get(key), StatisVO.class);
    }*/

    /*public void statisAndUpdateViewnum(Long strategyDetailId, int count) {
        String key = KeysUtil.STRATEGY_STATIS_VO.join(strategyDetailId.toString());
        StrategyDetail detail = strategyDetailService.get(strategyDetailId);
        StatisVO vo = new StatisVO();
        //判断redis中存不存在key
        if (redisTemplate.hasKey(key)) {
            //存在的话
            this.setStatis(strategyDetailId, count, StrategyStatisRedisServiceImpl.VIEWNUM);
        } else {
            //如果不存在的话
            copyProperties(detail, vo);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        }
    }

    public void setReplynumStatisRedis(Long detailId, int i) {
        setStatis(detailId, i, StrategyStatisRedisServiceImpl.REPLYNUM);
    }

    public JsonResult favor(Long sid, Long uId) {
        String uKey = KeysUtil.USER_STRATERY_STATIS_FAVOR.join(uId.toString());
        return getJsonResult(sid, uId, uKey, StrategyStatisRedisServiceImpl.FAVORNUM);
    }

    public JsonResult strategyThumbup(Long sId, Long uId) {
        String uKey = KeysUtil.USER_STRATERY_STATIS_FAVOR.join(uId.toString());
        return getJsonResult(sId, uId, uKey, StrategyStatisRedisServiceImpl.THUMBSUPNUM);
    }

    public void initRedisStatis() {
        List<StrategyDetail> list = strategyDetailService.list();
        for (StrategyDetail detail : list) {
            String key = KeysUtil.STRATEGY_STATIS_VO.join(detail.getId().toString());
            if (redisTemplate.hasKey(key)) {
                continue;
            }
            StatisVO vo = new StatisVO();
            copyProperties(detail, vo);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));

        }
    }

    public void redisPersistent()  {
        Set<String> keys = redisTemplate.keys(KeysUtil.STRATEGY_STATIS_VO.getName() + "*");
        for (String key : keys) {
            String s = redisTemplate.opsForValue().get(key);
            StatisVO vo = JSON.parseObject(s, StatisVO.class);
            StrategyDetail detail = new StrategyDetail();
            try {
                BeanUtils.copyProperties(detail,vo);
                detail.setId(vo.getStrategyId());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            strategyDetailService.updateReidsStatis(detail);
        }
        
    }

    private JsonResult getJsonResult(Long sid, Long uId, String uKey, int type) {
        List<Long> list = new ArrayList<>();
        //先判断redis中是否存在该key
        if (redisTemplate.hasKey(uKey)) {
            //存在的时候
            list = JSON.parseArray(redisTemplate.opsForValue().get(uKey), Long.class);
            if (list != null && list.contains(sid)) {
                if (type == StrategyStatisRedisServiceImpl.FAVORNUM) {
                    list.remove(sid);
                    redisTemplate.opsForValue().set(uKey, JSON.toJSONString(list));
                    return JsonResult.FAIL.addData(setStatis(sid, -1, StrategyStatisRedisServiceImpl.FAVORNUM));
                } else {
                    return JsonResult.FAIL;
                }
            }
        }
        //其他情况
        list.add(sid);
        if (type == StrategyStatisRedisServiceImpl.THUMBSUPNUM) {
            Date now = new Date();
            redisTemplate.opsForValue().set(uKey, JSON.toJSONString(list), DateUtil.getDateBetween(now, DateUtil.getEndDate(now)), TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(uKey, JSON.toJSONString(list));
        }
        return JsonResult.SUCCESS.addData(this.setStatis(sid, 1, type));
    }

    private void copyProperties(StrategyDetail detail, StatisVO vo) {
        try {
            BeanUtils.copyProperties(vo, detail);
            vo.setDestId(detail.getDest().getId());
            vo.setDestName(detail.getDest().getName());
            vo.setStrategyId(detail.getId());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
    private StatisVO setStatis(Long detailId, int i, int type) {
        String key = KeysUtil.STRATEGY_STATIS_VO.join(detailId.toString());
        StatisVO vo = this.getStatisRedis(key);
        switch (type) {
            case (StrategyStatisRedisServiceImpl.VIEWNUM):
                vo.setViewnum(vo.getViewnum() + i);
                break;
            case (StrategyStatisRedisServiceImpl.REPLYNUM):
                vo.setReplynum(vo.getReplynum() + i);
                break;
            case (StrategyStatisRedisServiceImpl.FAVORNUM):
                vo.setFavornum(vo.getFavornum() + i);
                break;
            case (StrategyStatisRedisServiceImpl.SHARENUM):
                vo.setSharenum(vo.getSharenum() + i);
                break;
            case (StrategyStatisRedisServiceImpl.THUMBSUPNUM):
                vo.setThumbsupnum(vo.getThumbsupnum() + i);
                break;
        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        return vo;
    }*/

}
